// CSV 转义
export const csvEscape = (value: unknown) => {
  const s = value == null ? '' : String(value);
  if (/[",\n]/.test(s)) {
    return '"' + s.replace(/"/g, '""') + '"';
  }
  return s;
};

// CSV 下载
export const downloadCsv = (filename: string, headers: string[], rows: (string | number)[][]) => {
  const headerLine = headers.map(csvEscape).join(',');
  const bodyLines = rows.map(r => r.map(csvEscape).join(',')).join('\n');
  const csv = headerLine + '\n' + bodyLines;
  const blob = new Blob(["\uFEFF" + csv], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  if (typeof link.download === 'undefined') {
    window.open(url, '_blank');
  } else {
    link.click();
  }
  setTimeout(() => {
    URL.revokeObjectURL(url);
  }, 100);
};

// XML 转义
export const xmlEscape = (value: unknown) => {
  const s = value == null ? '' : String(value);
  return s
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
};

// 构建 Excel XML
export const buildExcelXml = (headers: string[], rows: (string | number)[][]) => {
  const headerRow = '<Row>' + headers.map(h => `<Cell><Data ss:Type="String">${xmlEscape(h)}</Data></Cell>`).join('') + '</Row>';
  const dataRows = rows
    .map(r => '<Row>' + r.map(c => `<Cell><Data ss:Type="String">${xmlEscape(c)}</Data></Cell>`).join('') + '</Row>')
    .join('');
  return `<?xml version="1.0"?>\n`
    + `<?mso-application progid="Excel.Sheet"?>\n`
    + `<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">`
    + `<Worksheet ss:Name="Sheet1"><Table>${headerRow}${dataRows}</Table></Worksheet></Workbook>`;
};

// XLS 下载
export const downloadXls = (filename: string, headers: string[], rows: (string | number)[][]) => {
  const xml = buildExcelXml(headers, rows);
  const blob = new Blob([xml], { type: 'application/vnd.ms-excel' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename.endsWith('.xls') ? filename : `${filename}.xls`;
  if (typeof link.download === 'undefined') {
    window.open(url, '_blank');
  } else {
    link.click();
  }
  setTimeout(() => {
    URL.revokeObjectURL(url);
  }, 100);
};

// XLSX 下载
export const downloadXlsx = async (filename: string, headers: string[], rows: (string | number)[][]) => {
  try {
    const XLSX = await import('xlsx');
    const ws = XLSX.utils.aoa_to_sheet([headers, ...rows]);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    XLSX.writeFile(wb, filename);
  } catch (e) {
    alert('请先安装 xlsx 库: npm install xlsx');
  }
};

// CSV 解析
export const parseCsv = (text: string): string[][] => {
  const rows: string[][] = [];
  let i = 0, field = '', row: string[] = [], inQuotes = false;
  const pushField = () => { row.push(field); field = ''; };
  const pushRow = () => { rows.push(row); row = []; };
  while (i < text.length) {
    const ch = text[i];
    if (inQuotes) {
      if (ch === '"') {
        if (text[i + 1] === '"') { field += '"'; i += 2; continue; }
        inQuotes = false; i++; continue;
      } else { field += ch; i++; continue; }
    } else {
      if (ch === '"') { inQuotes = true; i++; continue; }
      if (ch === ',') { pushField(); i++; continue; }
      if (ch === '\n') { pushField(); pushRow(); i++; continue; }
      if (ch === '\r') { i++; continue; }
      field += ch; i++; continue;
    }
  }
  if (field.length > 0 || row.length > 0) { pushField(); pushRow(); }
  return rows.filter(r => r.length && r.some(c => c.trim() !== ''));
};

// Excel XML 解析
export const parseExcelXml = (text: string): string[][] => {
  try {
    const parser = new DOMParser();
    const doc = parser.parseFromString(text, 'application/xml');
    const rows: string[][] = [];
    const rowNodes = doc.getElementsByTagName('Row');
    for (let i = 0; i < rowNodes.length; i++) {
      const cells = rowNodes[i].getElementsByTagName('Cell');
      const row: string[] = [];
      for (let j = 0; j < cells.length; j++) {
        const data = cells[j].getElementsByTagName('Data')[0];
        row.push(data ? (data.textContent || '') : '');
      }
      if (row.length && row.some(c => c.trim() !== '')) rows.push(row);
    }
    return rows;
  } catch {
    return [];
  }
};

// XLSX 解析
export const parseXlsx = async (file: File): Promise<string[][]> => {
  try {
    const XLSX = await import('xlsx');
    const arrayBuffer = await file.arrayBuffer();
    const wb = XLSX.read(arrayBuffer, { type: 'array' });
    const ws = wb.Sheets[wb.SheetNames[0]];
    return XLSX.utils.sheet_to_json(ws, { header: 1, defval: '' }) as string[][];
  } catch (e) {
    if (e instanceof Error && e.message.includes('xlsx')) {
      throw new Error('请先安装 xlsx 库: npm install xlsx');
    }
    throw e;
  }
};

